const Koa = require('koa');
const cors = require('koa-cors');
const bodys = require('koa-body');
const request = require('request');
const staticFile = require('koa-static');

const fs = require('fs');
const path = require('path');
const util = require('util');
const exec = require('child_process').exec;
const app = new Koa();

// 跨域
app.use(cors());

app.use(bodys({
	multipart: true, // 支持文件上传
	formidable: {
		uploadDir: path.join(__dirname, 'public/upload/'), // 设置文件上传目录
		keepExtensions: true,    // 保持文件的后缀
		maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
		onFileBegin: (name, file) => { // 文件上传前的设置
			// console.log(`name: ${name}`);
			// console.log(file);
		},
	}
}));


app.use(staticFile(path.join(__dirname, '../public')));

// app.use(/* '/wxupload', */ (ctx) => {
app.use((ctx) => {
	console.log(`method:${ctx.method};`);
	console.log(`href  :${ctx.href};`);
	console.log(`ip    :${ctx.ip};`);
	console.log(`query :${util.inspect(ctx.query)};`);
	console.log(`body  :${util.inspect(ctx.body)};`);

	try {
		const { url, token } = ctx.request.body;
		const fp = `${__dirname}\\public\\`;
		const fn = `${Date.now()}.amr`;
		const out = `ny${Date.now()}.mp3`;


		request('http://127.0.0.1:5757/wx/get/access_token?sid=2&token=' + token,
			function (error, rs, body) {
				console.log('\nerror     :' + error);
				console.log('statusCode:' + (rs && rs.statusCode));
				console.log('body      :' + body);

				if (!error && rs && rs.statusCode === 200 && body) {
					body = body instanceof Object ? body : JSON.parse(body);
					const access_token = body.access_token;

					const pf = new Promise((resolve, reject) => {
						request(`https://api.weixin.qq.com/cgi-bin/media/get?access_token=${access_token}&media_id=${url}`).pipe(fs.createWriteStream(fp + fn), { encoding: 'GBK' });
						resolve(true);
					});

					exec('node -v', { encoding: 'GBK' }, (error, stdout, stderr) => {
						console.log(`\n 1.exec error:${error}; stdout:${util.inspect(stdout)}; stderr:${util.inspect(stderr)}`);
						console.log(`\n stdout:${stdout && stdout.toString()}`);
					});


					setTimeout(() => {
						console.log('5秒后開始執行了');
						// pf.then(() => {
							// let command = `ffmpeg -i ${fp + fn} -id3v2_version 3 ${fp + out}`;
							let command = `ffmpeg -i ${fp + fn} ${fp + out}`;
							console.log(`\n command:${command}`);

							exec(command, { encoding: 'GBK' }, (error, stdout, stderr) => {
								console.log(`\n 2.exec error:${error}; stdout:${util.inspect(stdout)}; stderr:${util.inspect(stderr)};`);

								console.log(`\n stdout:${stdout && stdout.toString()}`);
							});
						// });
					}, 5 * 1000);
				}
			}
		);


		ctx.body = { code: 200, data: fn };
	} catch (e) {
		console.log(`\n wxupload error:${e.message}`);
	}
});

console.log('http://ws.nuoya.io/');
console.log('http:127.0.0.1:3031/');
app.listen(3031);

